package com.zhb.cloud.config;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: DruidConfig
 * @Description:Druid 数据源配置
 * @author: zhb1316783262@163.com
 * @date: 2019年4月23日下午6:32:19
 */
@Configuration
@Slf4j
public class DataSourcesConfig {
	@Primary
	@ConfigurationProperties(prefix = "spring.datasource")
	@Bean(name="dataSource",initMethod="init",destroyMethod="close")
	public  DataSource druidDataSource() throws SQLException {
		log.info("数据源初始化");
		DruidDataSource dataSource = new DruidDataSource();
		return dataSource;
	}

	/**
	 * @MethodName: servletRegistrationBean
	 * @Description: druid 监控开启
	 * @Author: zhb1316783262@163.com
	 * @return ServletRegistrationBean
	 * @Date: 2019年4月23日下午6:21:16
	 */
	public @Bean ServletRegistrationBean<StatViewServlet> druidStatViewServlet() {
		ServletRegistrationBean<StatViewServlet> servletRegistrationBean = new ServletRegistrationBean<StatViewServlet>(
				new StatViewServlet(), "/druid/*");
		Map<String, String> initParams = new HashMap<>();
		// 可配的属性都在 StatViewServlet 和其父类下
		initParams.put("loginUsername", "admin");
		initParams.put("loginPassword", "admin");
		servletRegistrationBean.setInitParameters(initParams);
		return servletRegistrationBean;
	}

	/**
	 * @MethodName: druidWebStatFilter
	 * @Description: 资源过滤
	 * @Author: zhb1316783262@163.com
	 * @return FilterRegistrationBean<WebStatFilter>
	 * @Date: 2019年4月23日下午6:58:38
	 */
	public @Bean FilterRegistrationBean<WebStatFilter> druidWebStatFilter() {
		FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<WebStatFilter>(
				new WebStatFilter());
		Map<String, String> initParams = new HashMap<>();
		initParams.put("exclusions", "*.js,*.css,/druid/*");
		filterRegistrationBean.setInitParameters(initParams);
		filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
		return filterRegistrationBean;
	}
}
